package com.soufang.ui;

import java.io.InputStream;

import com.zxx.common.Common;
import com.zxx.sql.houseData;

import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class houseitemFragment extends Fragment implements OnPageChangeListener{
	
	/**
	 * @brief ViewPager
	 */
	private ViewPager viewPager;
	
	/**
	 * @brief装点点的ImageView数组
	 */
	private ImageView[] tips;
	
	/**
	 * @brief装ImageView数组
	 */
	private ImageView[] mImageViews;
	
		
	private int mimgCounts;
	private houseData mdata;
	private String mcity;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		//获取传过来的houseData参数
		mdata = new houseData();
		mdata = (houseData)getActivity().getIntent()
		            .getSerializableExtra(Common.KEY_HOUSE_ITEM);
		mcity = getActivity().getIntent().getStringExtra(Common.KEY_CITYINFO);
		 Log.i("houseitemActivity", mdata.getMtitle());
		//根据mdata的mpicpath1-5来获得图片数据的统计
		if(!CheckStrEmpty(mdata.getMpicPath1()))
		{
			++mimgCounts;
		}
		if(!CheckStrEmpty(mdata.getMpicPath2()))
		{
			++mimgCounts;
		}
		if(!CheckStrEmpty(mdata.getMpicPath3()))
		{
			++mimgCounts;
		}
		if(!CheckStrEmpty(mdata.getMpicPath4()))
		{
			++mimgCounts;
		}
		if(!CheckStrEmpty(mdata.getMpicPath5()))
		{
			++mimgCounts;
		}
	
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View contextView = inflater.inflate(R.layout.house_item_viewpager, container, false);
		
		ViewGroup group = (ViewGroup)contextView.findViewById(R.id.viewGroup);
		viewPager = (ViewPager)contextView.findViewById(R.id.imgviewPager);
		
		//将图片装载到数组中
		mImageViews = new ImageView[mimgCounts];
		for(int i=0; i<mImageViews.length; i++){
			ImageView imageView = new ImageView(getActivity());
			mImageViews[i] = imageView;
			switch(i)
			{
			  case 0:{
				  getDataPic(mdata.getMpicPath1(),imageView);
			  }
			  break;
			  case 1:{
				  getDataPic(mdata.getMpicPath2(),imageView);
			  }
			  break;
			  case 2:{
				  getDataPic(mdata.getMpicPath3(),imageView);
			  }
			  break;
			  case 3:{
				  getDataPic(mdata.getMpicPath4(),imageView);
			  }
			  break;
			  case 4:{
				  getDataPic(mdata.getMpicPath5(),imageView);
			  }
			  break;
			}
			
		}
		//将点点加入到ViewGroup中
		tips = new ImageView[mimgCounts];
		for(int i=0; i<tips.length; i++){
			ImageView imageView = new ImageView(getActivity());
	    	imageView.setLayoutParams(new LayoutParams(20,20));
	    	tips[i] = imageView;
	    	if(i == 0){
	    		tips[i].setBackgroundResource(R.drawable.page_indicator_focused);
	    	}else{
	    		tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);
	    	}
	    	
	    	 group.addView(imageView);
		}

		//设置Adapter
		viewPager.setAdapter(new MyAdapter());
		//设置监听，主要是设置点点的背景
		viewPager.setOnPageChangeListener(this);
		//设置ViewPager的默认项, 设置为长度的100倍，这样子开始就能往左滑动
		viewPager.setCurrentItem((mImageViews.length) * 100);
				
		reFreshData(contextView);
		return contextView;
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	private void getDataPic(String path,ImageView imgView){
		if(path != null){
		try {
		  AssetManager assetManager = getActivity().getAssets();
	      InputStream is = assetManager.open(path);
	      Bitmap bitmap = BitmapFactory.decodeStream(is);
	      if (bitmap != null) {
	    	  imgView.setImageBitmap(bitmap);
	    	  
	        }
		} catch (Exception e) {
	    	Log.e("houseitemFragment","we got big error here,Exception: "+Log.getStackTraceString(e));
	    }
	  }
	}
	
	
	
	@Override
	public void onPageScrollStateChanged(int arg0) {
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		
	}

	@Override
	public void onPageSelected(int arg0) {
		setImageBackground(arg0 % mImageViews.length);
	}
	
	/**
	 * @brief设置选中的tip的背景
	 * @param selectItems
	 */
	private void setImageBackground(int selectItems){
		for(int i=0; i<tips.length; i++){
			if(i == selectItems){
				tips[i].setBackgroundResource(R.drawable.page_indicator_focused);
			}else{
				tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);
			}
		}
	}
	
	private class MyAdapter extends PagerAdapter{

		@Override
		public int getCount() {
			return Integer.MAX_VALUE;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager)container).removeView(mImageViews[position % mImageViews.length]);
			
		}

		/**
		 * @brief载入图片进去，用当前的position 除以 图片数组长度取余数是关键
		 */
		@Override
		public Object instantiateItem(View container, int position) {
			((ViewPager)container).addView(mImageViews[position % mImageViews.length], 0);
			return mImageViews[position % mImageViews.length];
		}
		
		
		
	}
	
	/**
	 * @brief 检查传入的字符串是否是空的，s == ""在检查的时候会出错，最好还是利用长度检查
	 */
	private boolean CheckStrEmpty(String s){
		if(s == null || s.length()<=0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * @brief 刷新mdata上的数据到ui
	 */
   private void reFreshData(View view){
	   
	   Resources r = getActivity().getResources();
	   
	   TextView textTitle = (TextView)view.findViewById(R.id.textTitle);
	   textTitle.setText(mdata.getMtitle());
	   
	   TextView textPrice = (TextView)view.findViewById(R.id.textPrice);
	   String sellpriceText = r.getString(R.string.sellPrice);
	   String numText = String.valueOf(mdata.getMtotalprice());
	   String sW = r.getString(R.string.w);
	   String totalPriceText = sellpriceText +":"+numText+sW;
	   
	   //部分文字变换前景色为红色
	    int fstart=totalPriceText.indexOf(numText);
        int fend=fstart+numText.length()+sW.length();
        SpannableStringBuilder style=new SpannableStringBuilder(totalPriceText); 
        style.setSpan(new ForegroundColorSpan(Color.RED),fstart,fend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
	   textPrice.setText(style);
	   
	   TextView textorientation = (TextView)view.findViewById(R.id.textorientation);
	   String strcx = r.getString(R.string.buildcx)+ ":"+mdata.getMorientation();
	   textorientation.setText(strcx);
	   
	   TextView texthousetype = (TextView)view.findViewById(R.id.texthousetype);
	   String strBuildtype = r.getString(R.string.buildType) + ":"+mdata.getMhouseType();
	   texthousetype.setText(strBuildtype);
	   
	   TextView textzx = (TextView)view.findViewById(R.id.textzx);
	   String strdecode = r.getString(R.string.zx)+":"+mdata.getMdecorate();
	   textzx.setText(strdecode);
	   
	   TextView textArea = (TextView)view.findViewById(R.id.textArea);
	   String strArea = r.getString(R.string.area)+":"+mdata.getMarea();
	   textArea.setText(strArea);
	   
	   TextView textbuildType = (TextView)view.findViewById(R.id.textbuildType);
	   String strbuildType = r.getString(R.string.buildType)+":"+mdata.getMbuildType();
	   textbuildType.setText(strbuildType);
	   
	   TextView textFloor = (TextView)view.findViewById(R.id.textFloor);
	   String strFloor = r.getString(R.string.floor)+":"+mdata.getMlouchen();
	   textFloor.setText(strFloor);
	   
	   TextView textyear = (TextView)view.findViewById(R.id.textyear);
	   String buildAge = r.getString(R.string.year)+":"+String.valueOf(mdata.getMbuildAge());
	   textyear.setText(buildAge);
	   
	   Button btnTel = (Button)view.findViewById(R.id.btnTel);
	   String telStr = r.getString(R.string.tel)+":"+mdata.getMtel();
	   btnTel.setText(telStr);
	   //隐式intent拨打电话
	   btnTel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//拨打联系电话
				Uri uri = Uri.parse("tel:"+mdata.getMtel()); 
				Intent it = new Intent(Intent.ACTION_DIAL, uri);   
				startActivity(it); 

			}
		});
  
	   
	   Button btnMap = (Button)view.findViewById(R.id.btnMap);
	   btnMap.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//点击发送city给地图显示页面
				Bundle bundle= new Bundle();
				bundle.putSerializable(Common.KEY_MAPINFO,mcity);
				bundle.putSerializable(Common.KEY_DEPARTINFO,mdata.getMdepartMentName());
				Intent i = new Intent(getActivity(),mapActivity.class);
				i.putExtras(bundle);
				startActivity(i);
			}
		});
   }
}
